
/**
 * @ClassName Offer63
 * @Description 剑指 Offer 63. 股票的最大利润
 * @Author clockTown
 * @Date 2021/8/19 14:09
 * @Version 1.0
 */
class Offer63 {
}

/**
 * v0 dp数组
 */
class Offer63V0 {
    public int maxProfit(int[] prices) {
        if (prices.length <= 1){
            return 0;
        }
        int[] dp = new int[prices.length];
        dp[0] = 0;
        dp[1] = Math.max(0, prices[1] - prices[0]);
        int minPrice = Math.min(prices[1], prices[0]);
        for (int i = 2; i < prices.length; i++) {
            dp[i] = Math.max(dp[i - 1], prices[i] - minPrice);
            minPrice = Math.min(prices[i], minPrice);
        }
        return dp[prices.length - 1];
    }
}

/**
 * v1 不借助数组
 */
class Offer63V1 {
    public int maxProfit(int[] prices) {
        // cost表示最低买入价格， profit表示利润
        int cost = Integer.MAX_VALUE, profit = 0;
        for (int price : prices) {
            cost = Math.min(cost, price);
            profit = Math.max(profit, price - cost);
        }
        return profit;
    }
}